package com.xufx.algorithm.search;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

import java.util.Arrays;

/**
 * 二分查找
 * 先行条件：数组已经排序
 * 二分查找用迭代，不用递归
 */
public class BinarySearch {

    public static void main(String[] args) {
        int[] nums = new int[]{0,1,2,3,4,5,7,7,7,7,7,7,7,8,9,12};
        Arrays.sort(nums);
        int index = binarySearch(nums, 0, nums.length - 1, 7);
        System.out.println(index);
    }
    private static int binarySearch(int[] nums, int left, int right, int target){

        while(left <= right){
            int mid = right - (right - left) / 2;
            if (nums[mid] == target){
                return mid;
            }else if(nums[mid] > target){
                right = mid - 1;
            }else if (nums[mid] < target){
                left = mid + 1;
            }
        }
        return Integer.MIN_VALUE;
    }




}
